package com.cha.chaApp.baby.service.impl;

import com.cha.chaApp.baby.dao.BabyDao;
import com.cha.chaApp.baby.param.Alum;
import com.cha.chaApp.baby.service.BabyService;
import com.cha.chaCommon.core.entity.Baby;
import com.cha.chaCommon.core.exception.CustomerException;
import com.cha.chaCommon.core.utils.OssUtils;
import com.cha.chaCommon.core.utils.UserUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

@Service
public class BabyServiceImpl implements BabyService {

@Resource
private BabyDao babyDao;

    @Override
    public List<Baby> selectBaby() {

Integer uid=UserUtils.getUid();
        List<Baby> select = babyDao.select(uid);
        return select;

    }

    @Override
    public void addBaby(Baby baby) {
        Integer uid = UserUtils.getUid();
        System.out.println(uid);
        baby.setParentsId(uid);
        int i = babyDao.insertBaby(baby);

        if (i == 0) {
            throw new CustomerException("添加baby失败");
        }
    }



    @Override
    public String upload(InputStream fileInputStream, String originalFilename,Integer stage) {

        Integer uid = UserUtils.getUid();
        List<Baby> select = babyDao.select(uid);
        Baby baby = select.get(0);
        String s = OssUtils.uploadFile2OSS(fileInputStream, originalFilename);
        Alum alum = new Alum();
        alum.setImg(s);
        alum.setUploaderId(uid);
        alum.setBabyId(baby.getBabyId());
        alum.setStage(stage);
        babyDao.inserAlbum(alum);


     return s;

    }

    @Override
    public void delAlbum(String url) {
        babyDao.delAlbum(url);
//     url=url.replace("http://%s.%s/","");
//     int index=url.indexOf("?");
//     url=url.substring(0,index);
//        OSS ossClient = new OSSClientBuilder().build(OssUtils.ENDPOINT, OssUtils.ACCESS_KEY_ID, OssUtils.ACCESS_KEY_SECRET);
//        ossClient.deleteObject(OssUtils.BUCKET_NAME,url);
//        ossClient.shutdown();
    }



    @Override
    public void updateBaby(Baby baby) {
        int i = babyDao.updateBaby(baby);
        if (i == 0) {
            throw new CustomerException("修改baby失败");
        }
    }

    @Override
    public List<String> selectAlbum( Integer stage) {
        Baby baby = babyDao.select(UserUtils.getUid()).get(0);
        List<String> stringList = babyDao.selectAlbum(baby.getBabyId(), stage);
        return stringList;
    }


}
